import axios from 'axios'
import { Notification } from 'element-ui'
import { genID, genSign, getQueryString } from './utils'

const service = axios.create({
  timeout: 1000 * 60 * 2
})

service.interceptors.request.use(
  config => {
    const commonParams = {
      // _tId: genID(6),
      // _time: Date.parse(new Date()) / 1000,
      // _userInfo: getQueryString('userInfo'),
      userId: 'aHBfemh1c2hlbmdob25n'
    }

    if (config.method === 'get') {
      config.params = {
        ...config.params,
        ...commonParams
      }

      // const _sign = genSign(config.params)
      // config.params._sign = _sign
    }

    if (config.method === 'post') {
      config.data = {
        ...config.data,
        ...commonParams
      }

      // const _sign = genSign(config.data)
      // config.data._sign = _sign
    }

    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const { data } = response
    if (data.code !== '0000') {
      Notification({
        title: '错误',
        message: data.msg,
        type: 'error'
      })
      return Promise.reject(data)
    }

    return data.body
  },
  error => {
    // 请求超时或者网络有问题
    if (error.message.includes('timeout')) {
      Notification({
        title: '错误',
        message: '请求超时！请检查网络是否正常',
        type: 'error'
      })
    } else {
      Notification({
        title: '错误',
        message: '请求失败，请检查网络是否已连接',
        type: 'error'
      })
    }
    return Promise.reject(error)
  }
)

export default service
